package com.pinyoumei.app.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.icu.text.DecimalFormat;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.RelativeSizeSpan;

import com.pinyoumei.app.R;
import com.pinyoumei.app.application.Application;

import java.lang.ref.WeakReference;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {

    public static String startTime = "";
    public static String endTime = "";
    public static String isActivity = "1";//普通商品、2开心卷、3是礼包
    public static String happy_coupon = "";
    public static double red_package_amount = 0;

    //将银行金钱数转换成带有小数点并且后面加2个小0的形式
    public static SpannableString setBankNumText(String str){
        return changMoneyNumSize(addComma(str));
    }
    //对金钱数字做处理小数点后的数字变小
    public static SpannableString changMoneyNumSize(String value){
        SpannableString spannableString = new SpannableString(value);
        if (value.contains(".")) {
            spannableString.setSpan(new RelativeSizeSpan(0.6f), value.indexOf("."), value.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannableString;
    }
    //将没有逗号的字符串数字转换成加有逗号的字符串
    public static String addComma(String str){
        //DecimalFormat这个类只支持版本24的
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){//系统版本大于24
            DecimalFormat decimalFormat = new DecimalFormat("##0.00");//2,000,000.23这种金融数据
            return decimalFormat.format(Double.parseDouble(str));
        }else{
            return str;
        }
    }
    /**
     * 对字符串处理:将指定位置到指定位置的字符以星号代替
     *
     * @param content
     *            传入的字符串
     * @param begin
     *            开始位置
     * @param end
     *            结束位置
     * @return
     */
    public static String getStarString(String content, int begin, int end){

        if (begin >= content.length() || begin < 0) {
            return content;
        }
        if (end >= content.length() || end < 0) {
            return content;
        }
        if (begin >= end) {
            return content;
        }
        String starStr = "";
        for (int i = begin; i < end; i++) {
            starStr = starStr + "*";
        }
        return content.substring(0, begin) + starStr + content.substring(end);

    }

    /**
     * 对字符加星号处理：除前面几位和后面几位外，其他的字符以星号代替
     *
     * @param content
     *            传入的字符串
     * @param frontNum
     *            保留前面字符的位数
     * @param endNum
     *            保留后面字符的位数
     * @return 带星号的字符串
     */

    public static String getStarString2(String content, int frontNum, int endNum) {

        if (frontNum >= content.length() || frontNum < 0) {
            return content;
        }
        if (endNum >= content.length() || endNum < 0) {
            return content;
        }
        if (frontNum + endNum >= content.length()) {
            return content;
        }
        String starStr = "";
        for (int i = 0; i < (content.length() - frontNum - endNum); i++) {
            starStr = starStr + "*";
        }
        return content.substring(0, frontNum) + starStr
                + content.substring(content.length() - endNum);

    }
    /**
     * 获取当前本手机app的版本
     *
     * @param mContext
     * @return
     */
    public static int getVersionCode(Context mContext) {
        int versionCode = 0;
        try {
            //获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = mContext.getPackageManager().
                    getPackageInfo(mContext.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 获取app版本号名称
     *
     * @param context 上下文
     * @return
     */
    public static String getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().
                    getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }
    //生成随机数作为 订单号
    public static String getRandomOrder() {
        UUID uuid = UUID.randomUUID();
        String str = uuid.toString();
        String uuidStr = str.replace("-", "");
        String order = uuidStr.substring(0, 16);
        return order;
    }
    /*
     * 将时间戳转换为时间
     */
    public static String stampToDate(String s){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }
    /*
     * 将时间戳转换为时间年月日格式
     */
    public static String stampToDate2(String s){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }
    /*
     * 将时间戳转换为时间年月格式
     */
    public static String stampToDateOnly(String s){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }
    /*
     * 将时间戳转换为时间年月格式
     */
    public static String stampToDate3(String s){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }
    /*
     * 将时间yyyy-MM-dd HH:mm:ss转换为时间戳
     */
    public static String dateToStamp(String s) throws ParseException {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        Date date = simpleDateFormat.parse(s);
        long ts = date.getTime();
        res = String.valueOf(ts);
        return res;
    }
    /*
     * 将时间yyyy.MM.dd转换为时间戳
     */
    public static String datePointToStamp(String s) throws ParseException {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd");
        Date date = simpleDateFormat.parse(s);
        long ts = date.getTime();
        res = String.valueOf(ts);
        return res;
    }
    //影藏身份证
    public static String hideIdCard(String id){
        StringBuilder stringBuilder = new StringBuilder(id);
        stringBuilder.replace(4, 14, "****");
        return stringBuilder.toString();
    }
    //隐藏手机中间四位
    public static String hidePhoneNum(String phone) {
        String phone_s = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        return phone_s;
    }
    /**
     * 判断是否是手机号码
     *
     * @param inputStr
     * @return
     */
    public static boolean isMobilde(String inputStr){
        try {
            final String reg="^[1][3,4,5,6,7,8,9][0-9]{9}$";
            Pattern p=Pattern.compile(reg);
            Matcher m=p.matcher(inputStr);
            return m.matches();
        } catch (Exception e) {
            return false;
        }
    }


    @SuppressLint("StaticFieldLeak")
    private static Application sApplication;
    static WeakReference<Activity> sTopActivityWeakRef;
    static List<Activity> sActivityList = new LinkedList<>();

    private static Application.ActivityLifecycleCallbacks mCallbacks = new Application.ActivityLifecycleCallbacks() {
        @Override
        public void onActivityCreated(Activity activity, Bundle bundle) {
            sActivityList.add(activity);
            setTopActivityWeakRef(activity);
        }

        @Override
        public void onActivityStarted(Activity activity) {
            setTopActivityWeakRef(activity);
        }

        @Override
        public void onActivityResumed(Activity activity) {
            setTopActivityWeakRef(activity);
        }

        @Override
        public void onActivityPaused(Activity activity) {

        }

        @Override
        public void onActivityStopped(Activity activity) {

        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

        }

        @Override
        public void onActivityDestroyed(Activity activity) {
            sActivityList.remove(activity);
        }
    };

    private Utils() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    /**
     * 初始化工具类
     *
     * @param app 应用
     */
    public static void init(@NonNull final Application app) {
        Utils.sApplication = app;
        app.registerActivityLifecycleCallbacks(mCallbacks);
    }

    /**
     * 获取Application
     *
     * @return Application
     */
    public static Application getApp() {
        if (sApplication != null) return sApplication;
        throw new NullPointerException("u should init first");
    }

    private static void setTopActivityWeakRef(Activity activity) {
        if (sTopActivityWeakRef == null || !activity.equals(sTopActivityWeakRef.get())) {
            sTopActivityWeakRef = new WeakReference<>(activity);
        }
    }


    public static void copy(String content, Context context)
    {
// 得到剪贴板管理器
        ClipboardManager cmb = (ClipboardManager)context.getSystemService(Context.CLIPBOARD_SERVICE);
        cmb.setText(content.trim());

        ToastUtils.showLong("复制成功");
    }

    public static int getLevelIcon(String type){
        int levelIcon = 0;
        if(TextUtils.equals(type,"全部")){
            levelIcon = R.mipmap.icon_all1;
        }else if (TextUtils.equals(type,"用户")){
            levelIcon = R.mipmap.icon_yonghu1;
        }else if (TextUtils.equals(type,"会员")){
            levelIcon = R.mipmap.icon_huiyuan1;
        }else if (TextUtils.equals(type,"V1")){
            levelIcon = R.mipmap.icon_vip1_1;
        }else if (TextUtils.equals(type,"V2")){
            levelIcon = R.mipmap.icon_vip2_2;
        }else if (TextUtils.equals(type,"V3")){
            levelIcon = R.mipmap.icon_vip3_3;
        }else if (TextUtils.equals(type,"V4")){
            levelIcon = R.mipmap.icon_vip4_4;
        }else if (TextUtils.equals(type,"V5")){
            levelIcon = R.mipmap.icon_vip5_5;
        }
        return levelIcon;
    }

}
